// pages/authorization/authorization.js
import Ajax from '../../utils/request.js'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    authorizationStep: 1,
    hasUserInfo: false,
    userAuthData: {},
    userPhoneData: {},
    showReturnBtn: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  returnPageEvent() {
    wx.navigateBack({
      delta: 1
    })
  },
  cancelEvent() {
    wx.switchTab({
      url: '/pages/index/index',
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getUserInfoEvent();
  },
  async getWxLoginEvent(code, callbackEvent) {
    try {
      let res = await Ajax.get('/wxMiniProgram/wxLogin', {
        code
      });
      let data = res.result;
      app.globalData.phone = data.phone;
      wx.setStorageSync('wxAccessToken', data.wxAccessToken);
      callbackEvent(data.wxAccessToken)
    } catch (error) {
      console.log(error)
    }
  },
  getUserInfoEvent() {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    this.setData({
      userAuthData: e.detail,
      userInfo: e.detail.userInfo,
      hasUserInfo: true,
      authorizationStep: 2
    })

  },
  async getPhoneNumber(e) {
    if (e.detail.errMsg != 'getPhoneNumber:ok') {
      this.refusedEvent();
      return false;
    }
    this.setData({
      userPhoneData: e.detail
    })
    let {
      userAuthData,
      userPhoneData
    } = this.data;
    let parmas = {
      phoneData: {
        encryptedData: userPhoneData.encryptedData,
        iv: userPhoneData.iv,
      },
      encryptedData: userAuthData.encryptedData,
      rawData: userAuthData.rawData,
      iv: userAuthData.iv,
    }
    app.userInfoReadyCallback = res => {
      this.setData({
        userAuthData: userAuthData,
        userInfo: userAuthData.userInfo,
      })
    }
    wx.login({
      success: res => {
        app.globalData.appCode = res.code;
        this.getWxLoginEvent(res.code, async() => {
          try {
            let res = await Ajax.post('/wxMiniProgram/saveUserInfo', parmas);
            if (res.code != 1) {
              wx.showToast({
                title: res.errorMsg,
                icon: 'none',
                duration: 2000
              })
              // return false;
            } else {
              wx.switchTab({
                url: '/pages/index/index',
              });
            }
          } catch (error) {
            wx.showToast({
              title: res.errorMsg,
              icon: 'none',
              duration: 2000
            })
            console.log(error)
          }
        });
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  // 拒绝
  refusedEvent() {
    this.setData({
      authorizationStep: 1
    })
  },
})